#include "downloadservice.h"

DownloadService::DownloadService(QObject *parent) :
    QObject(parent)
{
}


void DownloadService::addDownload(const DownloadInfo* info)
{
    if (downloadsQueue.empty()){
        QTimer::singleShot(0, this, SLOT(newDownload()));
    }

    downloadsQueue.push(info);
}

void DownloadService::newDownload(){
    if (downloadsQueue.empty()) {
        return;
    }
    currentDownload = downloadsQueue.top();

    currentOutputFile.setFileName(currentDownload->getLocalAddress());
    if (!currentOutputFile.open(QIODevice::WriteOnly)) {
        qDebug() << "Problem with file " <<
                    currentDownload->getLocalAddress() <<
                    "skipping it.";
        downloadsQueue.pop();
        QTimer::singleShot(0, this, SLOT(newDownload()));
        return;
    }
    QUrl url = QUrl::fromUserInput(currentDownload->getInternetAddress());
    QNetworkRequest request(url);
    currentNeworkHandler = networkManager.get(request);

    connect(currentNeworkHandler, SIGNAL(downloadProgress(qint64,qint64)),
            SLOT(downloadProgress(qint64,qint64)));
    connect(currentNeworkHandler, SIGNAL(finished()),
            SLOT(finished()));
    connect(currentNeworkHandler, SIGNAL(readyRead()),
            SLOT(readyRead()));
}

void DownloadService::finished(){
    currentOutputFile.close();
    currentNeworkHandler->deleteLater();
    downloadsQueue.pop();
    currentDownload = 0;
    QTimer::singleShot(0, this, SLOT(newDownload()));
}

void DownloadService::readyRead(){
    currentOutputFile.write(currentNeworkHandler->readAll());
}

void DownloadService::downloadProgress(qint64 bytesReceived, qint64 bytesTotal){
    emit progressChanged(currentDownload, (double)bytesReceived/(double)bytesTotal);
}
